#!/usr/bin/env python

import pygtk
pygtk.require('2.0')
import gtk
import datetime
import modelo
import thread
import os
import sys
import locale
import gettext

class Vista:

    WINDOW_DEFAULT_WIDTH = 640
    WINDOW_DEFAULT_HEIGHT = 480
    
    message_name = None
    _ = None

    def delete_event(self, widget, event, data=None):
        # If you return FALSE in the "delete_event" signal handler,
        # GTK will emit the "destroy" signal. Returning TRUE means
        # you don't want the window to be destroyed.
        # This is useful for popping up 'are you sure you want to quit?'
        # type dialogs.

        # Change FALSE to TRUE and the main window will not be destroyed
        # with a "delete_event".
        return False

    def destroy(self, widget, data=None):
        gtk.main_quit()
        #thread.exit()

    #def insert_text(model,path,listiter,self, widget, buffer):
    #    iter = buffer.get_iter_at_offset(0)
    #    buffer.insert(iter,
    #                  "From: pathfinder@nasa.gov\n"
    #                  "To: mom@nasa.gov\n"
    #                  "Subject: Made it!\n"
    #                 "\n"
    #                  "We just got in this morning. The weather has been\n"
    #                  "great - clear but cold, and there are lots of fun sights.\n"
    #                  "Sojourner says hi. See you soon.\n"
    #                  " -Path\n")

    def insert_text(self, model,path,myiter,data=None):
    # print "Fila " + model.get_string_from_iter(myiter) +" seleccionada
        self.view.set_buffer(None)
        self.buffer = self.view.get_buffer()
        textiter = self.buffer.get_iter_at_offset(0)
        posicion = int(model.get_string_from_iter(myiter)) % len(self.lista)
        self.buffer.insert(textiter, self.controlador.obtener_Contenido(posicion))
        today = "%s" % datetime.date.today()
        statusbar_text = today + " - " + model.get_value(myiter,0) 
        self.statusbar.push(self.statusbar_counter,statusbar_text)
        self.statusbar_counter = self.statusbar_counter + 1
        
    def refresh(self,data=None):
        
        message = gtk.MessageDialog(None,gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
                                    gtk.BUTTONS_NONE, _("Actualizar puede tardar indefinidamente"))
        message.add_button(_("Cancelar"),gtk.RESPONSE_CLOSE)

        pb = gtk.ProgressBar(adjustment=None)
        
        message.vbox.pack_end(pb)
        
        pb.show()
        
        tid = thread.start_new_thread(self.complicatedOperation,(message,pb))
        #gtk.gdk.threads_enter()
        print >> sys.stderr, "Id del thread " + str(tid)

        resp = message.run()
        if resp== gtk.RESPONSE_CLOSE:
            message.destroy()
            self.controlador.matar_thread()
                
        #gtk.gdk.threads_leave()
        
    def complicatedOperation(self,dialog,progressBar):
        self.controlador.refresh(progressBar)
        dialog.response(gtk.RESPONSE_CLOSE)
        
            
    def change_selection(self,selection):
        selection.selected_foreach(self.insert_text)
        
    def name_callback(self, widget, entry,message):
        self.message_name = entry.get_text()
        message.response(gtk.RESPONSE_CLOSE)
        
    def add_row(self,data):
        message = gtk.MessageDialog(None,gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION,
                                    gtk.BUTTONS_NONE, _("Inserte el nombre del nuevo elemento"))
        message.add_button(_("Cancelar"),gtk.RESPONSE_CLOSE)

        name = gtk.Entry(15)
        name.connect("activate", self.name_callback, name,message)
        name.show()
        message.vbox.pack_end(name)

        resp = message.run()
        if resp== gtk.RESPONSE_CLOSE:
            if self.message_name <> None:
               self.controlador.anadir_fila(self.message_name)
               self.message_name=None 
            message.destroy()
        

    def __init__(self,controlador):
        locale.setlocale(locale.LC_ALL, '') 
        gettext.bindtextdomain('main', 'locale') 
        gettext.textdomain('main') 
        global _
        _ = gettext.gettext
        

        self.controlador = controlador

        self.counter = 0
        self.statusbar_counter = 0
        

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title(_("Practica 2"))
    
        self.window.connect("delete_event", self.delete_event)
    
        self.window.connect("destroy", self.destroy)
    
        # Sets the border width of the window.
        self.window.set_border_width(10)
    
        self.window.set_default_size(self.__class__.WINDOW_DEFAULT_WIDTH, self.__class__.WINDOW_DEFAULT_HEIGHT)

        menu_bar = gtk.MenuBar();


    # Menu Fichero
        file_menu = gtk.Menu();
    # open_item = gtk.MenuItem("Abrir");
    
        new_item = gtk.MenuItem(_("Nuevo"))
        new_item.connect("activate", self.add_row)

        accel_group = gtk.AccelGroup()
        self.window.add_accel_group(accel_group)
    
        new_item.add_accelerator("activate",accel_group,ord('N'),gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE)


        exit_item = gtk.MenuItem(_("Salir"))
        exit_item.connect("activate", self.destroy)
        exit_item.add_accelerator("activate",accel_group,ord('Q'),gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE)

    # file_menu.append(open_item);
        file_menu.append(new_item);
        file_menu.append(exit_item);

        file_item = gtk.MenuItem(_("Fichero"));

        file_item.set_submenu(file_menu);

        menu_bar.append(file_item);


    # Menu Editar
        edit_menu = gtk.Menu();
    
        edit_item = gtk.MenuItem(_("Editar"));

        edit_item.set_submenu(edit_menu);

        menu_bar.append(edit_item);

    #Menu Ver
        see_menu = gtk.Menu();
    
        see_item = gtk.MenuItem(_("Ver"));

        see_item.set_submenu(see_menu);

        menu_bar.append(see_item);


    #Menu Ayuda
        help_menu = gtk.Menu();
        about_item = gtk.MenuItem(_("Acerca de"));

        about_item.show();

        help_menu.append(about_item);

        help_item = gtk.MenuItem(_("Ayuda"));

        help_item.set_submenu(help_menu);

        menu_bar.append(help_item);


        toolbar = gtk.Toolbar()
        toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL)
        toolbar.set_style(gtk.TOOLBAR_BOTH)
        toolbar.set_border_width(5)

        new_icon = gtk.Image() #
        new_icon.set_from_file("icons/document-new.ico")
        new_button = toolbar.append_item(
            _("Nuevo"),
            _("Nuevo elemento"),
            "Private",
             new_icon,
             self.add_row)
        toolbar.append_space

        #new_button.connect_object("clicked", self.add_row,None)

        close_icon = gtk.Image() #
        close_icon.set_from_file("icons/system-log-out.ico")
        close_button = toolbar.append_item(
            _("Salir"),
            _("Salir de la aplicacion"),
            "Private",
             close_icon,
             self.destroy)
        toolbar.append_space 
        
        refresh_icon = gtk.Image() #
        refresh_icon.set_from_file("icons/view-refresh.ico")
        refresh_button = toolbar.append_item(
            _("Actualizar"),
            _("Operacion que se detiene indefinidamente"),
            "Private",
             refresh_icon,
             self.refresh)
        toolbar.append_space 

        vbox = gtk.VBox(False, 0)
        self.window.add(vbox)
        vbox.pack_start(menu_bar, False, False, 2)

        self.statusbar = gtk.Statusbar()
        vbox.pack_end(self.statusbar,False,False,0)

        hpane = gtk.HPaned()
        vbox.pack_end(hpane,True,True,2)

        vbox.pack_end(toolbar, False, False, 2)
        vbox.show()

    # Lista de elementos
        self.lista = gtk.ListStore(str)

        self.vlista = gtk.TreeView(self.lista)
        
        lcolumn = gtk.TreeViewColumn()

    #lcolumn.set_min_width(100)

        lcolumn.set_title(_("Mensajes"))
        self.vlista.append_column(lcolumn)

        cell = gtk.CellRendererText()
        
        colele = lcolumn.pack_start(cell, True)


        lcolumn.add_attribute(cell, 'text', 0)


        slista = self.vlista.get_selection()

        slista.set_mode(gtk.SELECTION_SINGLE)
        slista.connect("changed",self.change_selection)

        self.vlista.set_size_request(self.__class__.WINDOW_DEFAULT_WIDTH/4,-1)
    
        scrolled_list = gtk.ScrolledWindow()
        scrolled_list.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled_list.add(self.vlista)

    #hbox.pack_start(vlista, False, False, 2)
        hpane.pack1(scrolled_list,False,False)    

    #hbox.show()f
        self.vlista.show()


        self.view = gtk.TextView()
        self.view.set_editable(False)
        self.view.set_wrap_mode(gtk.WRAP_WORD)
        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scrolled_window.add(self.view)
        

        hpane.pack2(scrolled_window,True,False)

    
    #colele.connect("clicked", self.insert_text, mibuffer)

    
        # and the window
        self.window.show_all()
        
    def notificar(self, estado):
        #gtk.gdk.threads_enter()
        self.lista.append([estado])
        #gtk.gdk.threads_leave()